package com.caimiao.miao.interfaces;

import android.content.Context;

import com.caimiao.miao.service.MiaoService;

import java.lang.ref.WeakReference;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public abstract class BasePresenterImpl<V extends IBaseView, M extends IBaseModel> implements IBasePresenter {
    protected V mView;
    protected M mModel;
    protected MiaoService.LocalBinder mBinder;
    protected WeakReference<Context> mActivity;

    protected abstract M getModel();

    //将所有正在处理的Subscription都添加到CompositeSubscription中。统一退出的时候注销观察
    private CompositeDisposable mCompositeDisposable;

    public BasePresenterImpl(V mView) {
        this.mView = mView;
        mModel = getModel();
        mView.setPresenter(this);
    }

    @Override
    public void detach() {
        mView = null;
        mActivity = null;
        unDisposable();
    }

    @Override
    public CompositeDisposable getCompositeDisposable() {
        ////csb 如果解绑了的话添加 sb 需要新的实例否则绑定是无效的
        if (mCompositeDisposable == null || mCompositeDisposable.isDisposed()) {
            mCompositeDisposable = new CompositeDisposable();
        }
        return mCompositeDisposable;
    }

    @Override
    public void addDisposable(Disposable disposable) {
        getCompositeDisposable().add(disposable);
    }

    @Override
    public void unDisposable() {
        //在界面退出等需要解绑观察者的情况下调用此方法统一解绑，防止Rx造成的内存泄漏
        if (mCompositeDisposable != null) {
            mCompositeDisposable.dispose();
        }
    }

    @Override
    public void setBinder(MiaoService.LocalBinder binder) {
        mBinder = binder;
    }
}
